package com.king.first.app.uv;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashSet;


public class Project_UV_1 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> streamSource = env.readTextFile("input/UserBehavior.csv");

        //894923,3076029,1879194,pv,1511658000
        SingleOutputStreamOperator<Tuple2<String, Long>> behaviorStream = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] v = s.split(",");
                if ("pv".equals(v[3])) {
                    collector.collect(Tuple2.of("uv", Long.parseLong(v[0])));
                }
            }
        });

        SingleOutputStreamOperator<Integer> process = behaviorStream.keyBy(v -> v.f0).process(new KeyedProcessFunction<String, Tuple2<String, Long>, Integer>() {
            private HashSet<Long> ids = new HashSet<>();

            @Override
            public void processElement(Tuple2<String, Long> tuple2, KeyedProcessFunction<String, Tuple2<String, Long>, Integer>.Context context, Collector<Integer> collector) throws Exception {
                ids.add(tuple2.f1);
                collector.collect(ids.size());
            }
        });

        process.print();

        env.execute();
    }
}
